package ref_to_maps

import (
	"fmt"
	"reflect"
)

// MapToStruct 将map转换为结构体  dst 必须是指针
// Param:
// data map[string]any
// dst any 必须为指针
func MapToStruct(data map[string]any, dst any) {
	t := reflect.TypeOf(dst).Elem()
	v := reflect.ValueOf(dst).Elem()

	for i := 0; i < t.NumField(); i++ {
		field := t.Field(i)
		tag := field.Tag.Get("json")
		if tag == "" || tag == "-" {
			continue
		}

		mapField, ok := data[tag]
		fmt.Println("这是 mapField", mapField)
		if !ok {
			continue
		}

		val := v.Field(i)

		if field.Type.Kind() == reflect.Ptr {
			switch field.Type.Elem().Kind() {
			case reflect.String:
				mapFiledValue := reflect.ValueOf(mapField)
				if mapFiledValue.Type().Kind() == reflect.String {
					strVal := mapField.(string)
					val.Set(reflect.ValueOf(&strVal))
				}
			default:
				panic("unhandled default case")
			}
		}
	}
}
